#define _GNU_SOURCE
#include <stdio.h>
#include <dirent.h>
#include <signal.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>

int main(int argc, char **argv) {
    if (argc >= 2) {
        if (argc == 3 && strcmp(argv[1], "kill") == 0) {
            int pid = atoi(argv[2]);
            if (pid != 0) {
                int ret = kill(pid, SIGTERM);
                if (ret == 0) {
                    printf("杀死进程成功\n");
                } else {
                    printf("杀死进程失败\n");
                }
                return ret;
            } else {
                printf("无效的进程号\n");
                return 1;
            }
        } else {
            printf("用法: %s kill <PID>\n", argv[0]);
            return 1;
        }
    }

    DIR *dir;
    struct dirent *entry;

    dir = opendir("/proc");
    if (dir == NULL) {
        perror("Failed to open /proc");
        return 1;
    }

    char proc_path[PATH_MAX];
    while ((entry = readdir(dir)) != NULL) { // 遍历proc的所有目录项
        if (entry->d_type == DT_DIR) {
            int pid = atoi(entry->d_name);
            if (pid != 0) { // atoi返回非零，则pid是一个有效的进程号
                snprintf(proc_path, PATH_MAX, "/proc/%s/cmdline", entry->d_name);

                // 读取cmdline中的进程信息
                FILE *cmdline_file = fopen(proc_path, "r");
                if (cmdline_file) {
                    char cmdline[256];
                    fgets(cmdline, sizeof(cmdline), cmdline_file);

                    char *name = strrchr(cmdline, '/');
                    if (name != NULL) {
                        printf("进程号: %s, 名称: %s\n", entry->d_name, name + 1);
                    }

                    fclose(cmdline_file);
                }
            }
        }
    }

    closedir(dir);
    return 0;
}